const { Op } = require("sequelize");
const sequelize = appRequire('db');

const artClassModel = appRequire('models/artClass');
const artPPTModel = appRequire('models/artPPT');

// 导出对象，供其它模块调用
module.exports = {
    list,
};

async function list(req, request) {
    let postData = req.body
    let returnData = Common.clone(Constant.DEFAULT_SUCCESS);

    let checkResult = Common.checkUrl(postData, [], request);
    if (checkResult == false) return;

    let params = {}
    if (postData.artTypeClassId) params.artTypeClassId = postData.artTypeClassId
    let artType = await artClassModel.artType.findAll({
        where: params,
        order: [['createdAt', 'DESC']],
    })
    artType = Common.clone(artType)

    let artPptCount = await artPPTModel.findAll({
        where:{
            status:true
        },
        attributes: ['TypeId',
            [sequelize.fn('COUNT', sequelize.col('*')), '_count'],
        ],
        group: ['TypeId'],
    })
    artPptCount = Common.clone(artPptCount)

    for (let item of artType) {
        let newImages = []
        for (let image of item.images) {
            let thisImage = image.split("?imageMogr2/format/WebP")[0]
            if (thisImage.indexOf("/sf") == -1) thisImage = thisImage + "/sf"
            newImages.push(thisImage)
        }
        item.images = newImages
        item.count = 0
        let thisIndex = artPptCount.findIndex(thisItem => thisItem.TypeId == item.objectId)
        if (thisIndex != -1) item.count = artPptCount[thisIndex]._count
    }

    returnData.data = artType
    request.json(returnData)
}